/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Ucop/Crypto/Hmac.h"
#include "Ucop/Crypto/BigNumber.h"


namespace Ucop {
namespace Crypto {

	HmacHash::HmacHash()
	{
		std::uint8_t _Temp[SEED_KEY_SIZE] = { 0x38, 0xA7, 0x83, 0x15, 0xF8, 0x92,
			0x25, 0x30, 0x71, 0x98, 0x67, 0xB1, 0x8C, 0x4, 0xE2, 0xAA };
		memcpy(&_Mykey, &_Temp, SEED_KEY_SIZE);
		HMAC_CTX_init(&_Myctx);
		HMAC_Init_ex(&_Myctx, &_Mykey, SEED_KEY_SIZE, EVP_sha1(), NULL);
	}

	HmacHash::~HmacHash()
	{
		memset(&_Mykey, 0x00, SEED_KEY_SIZE);
		HMAC_CTX_cleanup(&_Myctx);
	}

	void HmacHash::UpdateBigNumber(BigNumber* _Bn)
	{
		UpdateData(_Bn->AsByteArray(), _Bn->GetNumBytes());
	}

	void HmacHash::UpdateData(const std::uint8_t* _Data, int _Size)
	{
		HMAC_Update(&_Myctx, _Data, _Size);
	}

	void HmacHash::Initialize()
	{
		HMAC_Init_ex(&_Myctx, &_Mykey, SEED_KEY_SIZE, EVP_sha1(), NULL);
	}

	void HmacHash::Finalize()
	{
		std::uint32_t _Size = 0;
		HMAC_Final(&_Myctx, _Mydigest, &_Size);
		UCOP_ASSERT(_Size == SHA_DIGEST_LENGTH);
	}

}}